package com.difsonapps.android.marker.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.R.menu;
import com.difsonapps.android.marker.adapters.AlbumGridAdapter;
import com.difsonapps.android.marker.adapters.ImportFacebookAlbumsAdapter;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Album;
import com.difsonapps.android.marker.beans.User;
import com.difsonapps.android.marker.fragments.AlbumsFragment;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.Session.StatusCallback;
import com.facebook.model.GraphObject;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.listeners.OnPhotosListener;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class ImportFacebookAlbumsActivity extends Activity {
    static final String PENDING_REQUEST_BUNDLE_KEY = "com.difsonapps.android.marker:PendingRequest";
    Session session;
    boolean pendingRequest;
	public static final String EXTRAS_ALBUMS_IMPORT = "com.difsonapps.android.marker.beans.facebook.Albums";
	List<com.difsonapps.android.marker.beans.facebook.Album> albums;
	private boolean testMode = true;
	SimpleFacebook mSimpleFacebook;
    private static final String TAG = ImportFacebookAlbumsActivity.class.getSimpleName();
    private ListView gridView;
    private ImportFacebookAlbumsAdapter gridAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_import_facebook_albums);
		
		albums = getIntent().getParcelableArrayListExtra(EXTRAS_ALBUMS_IMPORT);
		if(albums==null||albums.isEmpty()){
			loadTestAlbums();
		}
		gridView = (ListView) findViewById(R.id.gridListAlbum);
		gridAdapter = new ImportFacebookAlbumsAdapter(this, albums);
        gridView.setAdapter(gridAdapter);
		
		//New facebook
        this.session = createSession();
        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
        loadCouverture();
	}
	
	public void loadTestAlbums(){
		if(testMode){
			
		}
	}
	
	public void btnImportClick(View view){
		toast("Starting...");
		for(com.difsonapps.android.marker.beans.facebook.Album album : albums){
			album.setStatus(com.difsonapps.android.marker.beans.facebook.Album.STATUS_STARTED);			
		}
		gridAdapter.notifyDataSetChanged();
		loadCreateAlbum(0);
	}
	
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.import_facebook_albums, menu);
		return true;
	}

	
	@Override
	public void onResume() {
	    super.onResume();
	    mSimpleFacebook = SimpleFacebook.getInstance(this);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (this.session.onActivityResult(this, requestCode, resultCode, data) &&
                this.session.getState().isOpened()) {
            if(requestCouverturPending) loadCouverture();
            if(pendingRequest) sendRequests();
        } 
	    mSimpleFacebook.onActivityResult(this, requestCode, resultCode, data); 
	    super.onActivityResult(requestCode, resultCode, data);
	}
	

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        pendingRequest = savedInstanceState.getBoolean(PENDING_REQUEST_BUNDLE_KEY, pendingRequest);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putBoolean(PENDING_REQUEST_BUNDLE_KEY, pendingRequest);
    }
	public void toast(String text){
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
	boolean requestCouverturPending = false;
	void loadCouverture (){
		if(!session.isOpened()){
			requestCouverturPending = true;
			this.session = Session.openActiveSession(this, true, callback);
        	return;
		}
		requestCouverturPending = false;
		for(com.difsonapps.android.marker.beans.facebook.Album album : albums){
			loadCouverture(album);
		}
	}
	
	void loadCouverture (final com.difsonapps.android.marker.beans.facebook.Album album){
    	/*if(!this.session.isOpened()) {
        	this.session = Session.openActiveSession(this, true, callback);
        	return;
        }*/
    	Bundle params = new Bundle();
    	params.putString("fields", "picture,images");
    	new Request(
			    session,
			    "/"+album.getCoverPhotoId(),
			    params,
			    HttpMethod.GET,
			    new Request.Callback() {
					
					@Override
					public void onCompleted(com.facebook.Response response) {
						//Log.d("Requested photo", response.toString());
				        try {
							GraphObject go  = response.getGraphObject();
					        JSONObject  jso = go.getInnerJSONObject();
					        Log.d("Requested photo", jso.toString());
					        String picture = jso.getString("picture");
					        Log.d("Requested photo picture", picture);
					        
					        if(true){
					        	for(com.difsonapps.android.marker.beans.facebook.Album album2 : albums){
					        		if(album2.getFid()==album.getFid()){
					        			album2.setCoverPhotoSrc(picture);
					        			gridAdapter.notifyDataSetChanged();
					        		}
					        	}
					        }
							/*JSONArray   arr = jso.getJSONArray( "data" );
							List<com.difsonapps.android.marker.beans.facebook.Album> albums = new ArrayList<com.difsonapps.android.marker.beans.facebook.Album>();
							for ( int i = 0; i < ( arr.length() ); i++ )
					        {
					            JSONObject json_obj = arr.getJSONObject( i );
					            String id     = json_obj.getString("id");
					            String name   = json_obj.getString("name");
					            String description = json_obj.has("description")?json_obj.getString("description" ):"";
					            String cover_photo = json_obj.getString("cover_photo" );
					            int count = json_obj.has("count")?json_obj.getInt("count"):0;
					            albums.add(new com.difsonapps.android.marker.beans.facebook.Album(id, name, description, cover_photo, count));
					            //Log.d("Facebook Photo ID", id);
					        }
							loadCheckNewAlbums(albums);
							*/
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						// TODO Auto-generated method stub
						
					}
				}
			).executeAsync();
    }
	
	public int currentAlbumPosition = 0;
	public void loadCreateAlbum(int position){
		if(position>albums.size()-1) return;
		currentAlbumPosition = position;
		toast("Starting import of position "+position);
		com.difsonapps.android.marker.beans.facebook.Album album = albums.get(position);
		if(!album.isCheched()) {
			loadCreateAlbum(position+1);
			return;
		}
		album.setStatus(com.difsonapps.android.marker.beans.facebook.Album.STATUS_PENDING);
		gridAdapter.notifyDataSetChanged();
		
		Map<String, String> params = new HashMap<String, String>();
        params.put("id", album.getFid());
        params.put("name", album.getName());
        params.put("path", album.getCoverPhotoId());
        params.put("description", album.getDescription());
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.createAlbumFacebookUrl, 
				params,
				new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonCreateAlbum(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	toast("Error: " + error.getMessage());
                    	Log.e("Test", error.getMessage());
                    	com.difsonapps.android.marker.beans.facebook.Album currentAlbum = albums.get(currentAlbumPosition);
                    	currentAlbum.setStatus(com.difsonapps.android.marker.beans.facebook.Album.STATUS_FAILED);
    	            	gridAdapter.notifyDataSetChanged();
    	            	//TODO Continuer
                    }
                }
        );
       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void parseJsonCreateAlbum(JSONObject response){
		try {
			com.difsonapps.android.marker.beans.facebook.Album currentAlbum = albums.get(currentAlbumPosition);
			if(response.has("result_code")){
				String resultCode = response.getString("result_code");
				if(resultCode.equals("success")){
					Album album = Album.parseFromJsonObject(response.getJSONObject("album"));
					currentAlbum.setId(album.getId());
					sendRequests();
					//loadAlbumsPhoto(currentAlbum.getFid());//Chargement des photos facebook de l'album
					return;
	            	
				}else /*if(response.has("error"))*/{
					currentAlbum.setStatus(com.difsonapps.android.marker.beans.facebook.Album.STATUS_FAILED);
	            	gridAdapter.notifyDataSetChanged();
	            }
			}
        } catch (JSONException e) {
            e.printStackTrace();
        }
		//TODO Continuer
	}
	
	private void loadAlbumsPhoto(String albumId){
		mSimpleFacebook.getPhotos(albumId, onPhotosListener);
	}
	
	OnPhotosListener onPhotosListener = new OnPhotosListener() {            
	    @Override
	    public void onComplete(List<com.sromku.simple.fb.entities.Photo> photos) {
	    	Map<String, String> params = new HashMap<String, String>();
	    	if(photos.isEmpty()) loadCreateAlbum(currentAlbumPosition++);//TODO Afficher le status avant de passer au traitement de l'album suivant
	    	com.difsonapps.android.marker.beans.facebook.Album currentAlbum = albums.get(currentAlbumPosition);
	        params.put("id", ""+currentAlbum.getId());//album id
	        params.put("nb_photos", ""+(photos.size()));
	        int i = 1;
	        for(com.sromku.simple.fb.entities.Photo photo : photos){
		        params.put("name"+i, photo.getName());
		        params.put("path"+i, (photo.getImageSources().isEmpty())?photo.getIcon():photo.getImageSources().get(0).getSource());
		        params.put("id_facebook"+i, photo.getId());
		        i++;
	        }
			CustomRequest jsObjRequest = new CustomRequest(
					Method.POST, 
					AppConstant.importPhotosFacebookUrl, 
					params,
					new Response.Listener<JSONObject>() {
	                    @Override
	                    public void onResponse(JSONObject response) {
	                    	toast("Response : "+response.toString());
	                    	Log.i("Test", response.toString());
	                    	parseJsonImportPhotos(response);
	                    }
	                },
	                new Response.ErrorListener() {
	 
	                    @Override
	                    public void onErrorResponse(VolleyError error) {
	                    	toast("Error: " + error.getMessage());
	                    	Log.e("Test", error.getMessage());
	                    	com.difsonapps.android.marker.beans.facebook.Album currentAlbum = albums.get(currentAlbumPosition);
	                    	currentAlbum.setStatus(com.difsonapps.android.marker.beans.facebook.Album.STATUS_FAILED);
	    	            	gridAdapter.notifyDataSetChanged();
	    	            	//TODO Continuer
	                    }
	                }
	        );
	       AppController.getInstance().addToRequestQueue(jsObjRequest);
	    }

	    /* 
	     * You can override other methods here: 
	     * onThinking(), onFail(String reason), onException(Throwable throwable)
	     */     
	};
	
	private void parseJsonImportPhotos(JSONObject response){
		try {
			com.difsonapps.android.marker.beans.facebook.Album currentAlbum = albums.get(currentAlbumPosition);
			if(response.has("result_code")){
				String resultCode = response.getString("result_code");
				if(resultCode.equals("success")){
					Album album = Album.parseFromJsonObject(response.getJSONObject("album"));
					int nb = response.has("nb")?response.getInt("nb"):0;
					currentAlbum.setId(album.getId());
					currentAlbum.setCountUploaded(currentAlbum.getCountUploaded()+nb);
					currentAlbum.setCoverPhotoSrc(album.getImage());
					currentAlbum.setStatus(com.difsonapps.android.marker.beans.facebook.Album.STATUS_IMPORTED);
					gridAdapter.notifyDataSetChanged();
					//toast("New current position : "+(currentAlbumPosition+1));
					loadCreateAlbum(currentAlbumPosition+1);
					return;
	            	
				}else /*if(response.has("error"))*/{
					currentAlbum.setStatus(com.difsonapps.android.marker.beans.facebook.Album.STATUS_FAILED);
	            	gridAdapter.notifyDataSetChanged();
	            }
			}
        } catch (JSONException e) {
            e.printStackTrace();
        }
		//TODO Continuer
	}
	
	StatusCallback callback = new StatusCallback() {
        public void call(Session session, SessionState state, Exception exception) {
            if (exception != null) {
                new AlertDialog.Builder(ImportFacebookAlbumsActivity.this)
                        .setTitle(R.string.an_error_occured)
                        .setMessage(exception.getMessage())
                        .setPositiveButton(R.string.ok_button, null)
                        .show();
                ImportFacebookAlbumsActivity.this.session = createSession();
            }
            else if(pendingRequest) sendRequests();
            else if(requestCouverturPending) loadCouverture();
        }
    };
    private Session createSession() {
        Session activeSession = Session.getActiveSession();
        if (activeSession == null || activeSession.getState().isClosed()) {
            activeSession = new Session.Builder(this).setApplicationId(getResources().getString(R.string.app_id)).build();
            Session.setActiveSession(activeSession);
        }
        return activeSession;
    }
    
    private void sendRequests() {
    	//getHask();
    	//if(true) return;
    	
    	toast("Executing request...");
    	if(!this.session.isOpened()) {
    		pendingRequest = true;
        	this.session = Session.openActiveSession(this, true, callback);
        	return;
        }
    	if(currentAlbumPosition<0 || currentAlbumPosition>=albums.size()){
    		pendingRequest = false;
    		return;
    	}
    	com.difsonapps.android.marker.beans.facebook.Album currentAlbum = albums.get(currentAlbumPosition);
    	Bundle params0 = new Bundle();
    	params0.putString("fields", "id,name,images,picture,source,description");
    	new Request(
			    session,
			    "/"+currentAlbum.getFid()+"/photos",
			    params0,
			    HttpMethod.GET,
			    new Request.Callback() {
					
					@Override
					public void onCompleted(com.facebook.Response response) {
						pendingRequest = false;
						Log.d("Request photos", response.toString());
				        try {
							GraphObject go  = response.getGraphObject();
					        JSONObject  jso = go.getInnerJSONObject();
							JSONArray   arr = jso.getJSONArray( "data" );
							//List<com.difsonapps.android.marker.beans.facebook.Album> albums = new ArrayList<com.difsonapps.android.marker.beans.facebook.Album>();
							Map<String, String> params = new TreeMap<String, String>();
							if(arr==null|| arr.length()==0) loadCreateAlbum(currentAlbumPosition++);//TODO Afficher le status avant de passer au traitement de l'album suivant
					    	com.difsonapps.android.marker.beans.facebook.Album currentAlbum = albums.get(currentAlbumPosition);
					        params.put("id", ""+currentAlbum.getId());//album id
					        params.put("nb_photos", ""+(arr.length()));
					        
							for ( int i = 0; i < ( arr.length() ); i++ )
					        {
					            JSONObject json_obj = arr.getJSONObject( i );
					            String id     = json_obj.getString("id");
					            String name   = json_obj.has("name")?json_obj.getString("name"):"";
					            String description = json_obj.has("description")?json_obj.getString("description" ):"";
					            String image = json_obj.has("source")?json_obj.getString("source"):"";
					            //Log.d("Facebook Photo SOURCE 1", image);
					            int count = json_obj.has("count")?json_obj.getInt("count"):0;
					            if("".equals(image)){
					            	JSONArray json_images = json_obj.has("images")?json_obj.getJSONArray("images"):null;
					            	if(json_images!=null){
					            		image = json_images.getJSONObject(0).getString("source");
					            	}
					            }
					            
					            int pos = i+1;
					            params.put("name"+pos, name);
						        params.put("path"+pos,image);
						        params.put("id_facebook"+pos, id);
					            //albums.add(new com.difsonapps.android.marker.beans.facebook.Album(id, name, description, cover_photo, count));
					            //Log.d("Facebook Photo ID", id);
					            //Log.d("Facebook Photo SOURCE 2", image);
					        }
							
					        //int i = 1;
					        /*for(com.sromku.simple.fb.entities.Photo photo : photos){
						        params.put("name"+i, photo.getName());
						        params.put("path"+i, (photo.getImageSources().isEmpty())?photo.getIcon():photo.getImageSources().get(0).getSource());
						        params.put("id_facebook"+i, photo.getId());
						        i++;
					        }*/
							CustomRequest jsObjRequest = new CustomRequest(
									Method.POST, 
									AppConstant.importPhotosFacebookUrl, 
									params,
									new Response.Listener<JSONObject>() {
					                    @Override
					                    public void onResponse(JSONObject response) {
					                    	toast("Response : "+response.toString());
					                    	Log.i("Test", response.toString());
					                    	parseJsonImportPhotos(response);
					                    }
					                },
					                new Response.ErrorListener() {
					 
					                    @Override
					                    public void onErrorResponse(VolleyError error) {
					                    	toast("Error: " + error.getMessage());
					                    	Log.e("Test", error.getMessage());
					                    	com.difsonapps.android.marker.beans.facebook.Album currentAlbum = albums.get(currentAlbumPosition);
					                    	currentAlbum.setStatus(com.difsonapps.android.marker.beans.facebook.Album.STATUS_FAILED);
					    	            	gridAdapter.notifyDataSetChanged();
					    	            	//TODO Continuer
					                    }
					                }
					        );
					       AppController.getInstance().addToRequestQueue(jsObjRequest);
							//loadCheckNewAlbums(albums);
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						// TODO Auto-generated method stub
						
					}
				}
			).executeAsync();
    	
    }
	
}
